package com.csailing4cloud.csailing.auth.endpoint;

import cn.hutool.core.util.StrUtil;
import com.csailing4cloud.csailing.common.core.constants.CommonConstants;
import com.csailing4cloud.csailing.common.core.util.CsResponse;
import lombok.AllArgsConstructor;
import org.springframework.cache.CacheManager;
import org.springframework.http.HttpHeaders;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author dyh
 */
@RestController
@AllArgsConstructor
@RequestMapping("/token")
public class CsailingTokenEndPoint {

    private final TokenStore tokenStore;
    private final CacheManager cacheManager;

    @GetMapping("/login")
    public ModelAndView require() {
        return new ModelAndView("ftl/login");
    }

    /**
     * 退出token
     *
     * @param authHeader Authorization
     */
    @DeleteMapping("/logout")
    public CsResponse logout(@RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authHeader) {
        if (StrUtil.isBlank(authHeader)) {
            return CsResponse.builder()
                    .code(CommonConstants.FAIL)
                    .result(Boolean.FALSE)
                    .message("退出失败，token 为空").build();
        }

        String tokenValue = authHeader.replace("Bearer", "").trim();
        OAuth2AccessToken accessToken = tokenStore.readAccessToken(tokenValue);
        if (accessToken == null || StrUtil.isBlank(accessToken.getValue())) {
            return CsResponse.builder()
                    .code(CommonConstants.FAIL)
                    .result(Boolean.FALSE)
                    .message("退出失败，token 无效").build();
        }

        OAuth2Authentication auth2Authentication = tokenStore.readAuthentication(accessToken);
        cacheManager.getCache("user_details")
                .evict(auth2Authentication.getName());
        tokenStore.removeAccessToken(accessToken);
        return  CsResponse.success(Boolean.TRUE);
    }

}
